package org.prail.ui;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import org.prail.ui.utils.CustomButton;
import org.prail.wrappers.SearchResult;

public class ResultsTable extends JTable {
	private static final long serialVersionUID = 1606032586018350624L;
	public static DefaultTableModel model = new DefaultTableModel();
	private static ResultsTable instance = null;
	public static HashMap<Integer, SearchResult> tableList = new HashMap<Integer, SearchResult>();
	private static CustomButton stream = new CustomButton("Play");

	public ResultsTable() {
		super();
		instance = this;
		getTableHeader().setReorderingAllowed(false); // disable moving columns
		setModel(model);
		updateModel();
		addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					JTable target = (JTable) e.getSource();
					int row = target.getSelectedRow();
					final SearchResult selected = tableList.get(row);
					System.out.println("Downloading: " + selected.toString());
					DownloadTable.get().download(selected);
				}
			}
		});
	}
	
	public static int getRow(SearchResult r) {
		for(int a : tableList.keySet()) {
			if(tableList.get(a).equals(r)) {
				return a;
			}
		}
		return -1;
	}

	private void updateModel() {
		model.addColumn("Artist");
		model.addColumn("Title");
		model.addColumn("Length");
		model.addColumn("Bitrate");
		model.addColumn("Stream");
		getColumnModel().getColumn(4).setCellRenderer(stream);
		getColumnModel().getColumn(4).setCellEditor(stream);
		TableColumn c = getColumnModel().getColumn(2); // length column
		c.setMaxWidth(70); // max width
		c.setMinWidth(50); // min width
		c = getColumnModel().getColumn(3);
		c.setMinWidth(70);
		c.setMaxWidth(70);
		c = getColumnModel().getColumn(4);
		c.setMinWidth(70);
		c.setMaxWidth(70);
	}

	public void empty() {
		tableList.clear();
		if (model.getRowCount() > 0) {
			model = new DefaultTableModel();
			setModel(model);
			updateModel();
			CustomButton.buttons.clear();
		}
	}

	public static ResultsTable get() {
		return instance;
	}

	public void add(final SearchResult r) {
		final Object[] row = new Object[] { r.getArtist(), r.getTitle(),
				r.getLength(), "Unknown", new CustomButton("Play") };
		model.addRow(row);
		tableList.put(tableList.size(), r);
		r.start();
	}

	@Override
	public boolean isCellEditable(int rowIndex, int vColIndex) {
		return vColIndex == 4;
	}

}
